package com.jsu.clubmanagementsystem.service.club.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jsu.clubmanagementsystem.common.ErrorCode;
import com.jsu.clubmanagementsystem.common.PageQueryRequest;
import com.jsu.clubmanagementsystem.exception.BusinessException;
import com.jsu.clubmanagementsystem.mapper.ClubMapper;
import com.jsu.clubmanagementsystem.model.dto.clubannouncement.ClubAnnouncementQueryRequest;
import com.jsu.clubmanagementsystem.model.entity.Club;
import com.jsu.clubmanagementsystem.model.entity.ClubAnnouncement;
import com.jsu.clubmanagementsystem.model.vo.clubAnnouncement.ClubAnnouncementVO;
import com.jsu.clubmanagementsystem.mapper.ClubAnnouncementMapper;
import com.jsu.clubmanagementsystem.model.vo.clubAnnouncement.ListAnnouncementVO;
import com.jsu.clubmanagementsystem.service.club.ClubAnnouncementService;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
* @author 24753
* @description 针对表【club_announcement(社团公告)】的数据库操作Service实现
* @createDate 2025-05-13 17:19:16
*/
@Service
public class ClubAnnouncementServiceImpl extends ServiceImpl<ClubAnnouncementMapper, ClubAnnouncement>
        implements ClubAnnouncementService {

    @Resource
    @Lazy
    private ClubMapper clubMapper;

    @Override
    public ClubAnnouncementVO getAnnouncementVo(ClubAnnouncement announcement) {
        ClubAnnouncementVO announcementVO = ClubAnnouncementVO.objToVo(announcement);
        return announcementVO;
    }

    @Override
    public ClubAnnouncementVO getAnnouncementVoById(Long id) {
        if (id == null || id <= 0) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "参数错误");
        }
        ClubAnnouncement announcement = this.getByIdIncludeDeleted(id);
        if (announcement == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND, "请求数据不存在");
        }
        return this.getAnnouncementVo(announcement);
    }

    @Override
    public ClubAnnouncement getByIdIncludeDeleted(Long id) {
        return baseMapper.getByIdIncludeDeleted(id);
    }

    @Override
    public List<ClubAnnouncement> getAllLogicAnnouncements(ClubAnnouncementQueryRequest queryRequest) {
        // xml自定义sql语句 + Mapper自定义方法 + lambdaQueryWrapper 实现查询已经逻辑删除和未删除的数据
        LambdaQueryWrapper<ClubAnnouncement> queryWrapper = Wrappers.<ClubAnnouncement>lambdaQuery();
        Long id = queryRequest.getId();
        Long clubId = queryRequest.getClubId();
        String title = queryRequest.getTitle();

        queryWrapper.eq(ObjectUtils.isNotEmpty(id), ClubAnnouncement::getId, id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(clubId), ClubAnnouncement::getClubId, clubId);
        queryWrapper.like(StringUtils.isNotBlank(title), ClubAnnouncement::getTitle, title);

        //按时间倒序
        queryWrapper.orderByDesc(ClubAnnouncement::getCreateTime);
        List<ClubAnnouncement> announcementList = this.baseMapper.findAllAnnouncements(queryWrapper);
        return announcementList;
    }

    @Override
    public Page<ClubAnnouncementVO> getAnnouncementVoPage(Page<ClubAnnouncement> page) {
        List<ClubAnnouncement> announcementList = page.getRecords();
        List<ClubAnnouncementVO> announcementVOList = announcementList.stream()
                .map(announcement -> {
                    return this.getAnnouncementVo(announcement);
                })
                .collect(Collectors.toList());

        long total = page.getTotal();
        long size = page.getSize();
        long current = page.getCurrent();
        Page<ClubAnnouncementVO> voPage = new Page<>(current, size, total);
        voPage.setRecords(announcementVOList);
        return voPage;
    }

    @Override
    public void validateAnnouncement(ClubAnnouncement announcement) {
        Long clubId = announcement.getClubId();
        String title = announcement.getTitle();
        String content = announcement.getContent();
        if (ObjectUtils.isEmpty(clubId) || clubId <= 0) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "参数为空");
        }
        if (StringUtils.isAnyBlank(title, content)) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "参数为空");
        }
        if (title.length() > 512) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "公告标题过长");
        }
        if (content.length() > 8192) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "公告内容过长");
        }
    }

    @Override
    public Page<ListAnnouncementVO> getAllAnnouncements(PageQueryRequest page) {
        String query = page.getQuery();
        Page<ClubAnnouncement> iPage=new Page<>(page.getCurrent(), page.getPageSize());
        List<ClubAnnouncement> clubAnnouncements=null;
        QueryWrapper<ClubAnnouncement> queryWrapper=new QueryWrapper<>();
        if(query!=null) {
            queryWrapper.like("title",query);
        }
        clubAnnouncements = this.baseMapper.selectWrapper(iPage,queryWrapper);
        List<ListAnnouncementVO> listAnnouncementVOS = convertAnnouncement(clubAnnouncements);
        return new Page<ListAnnouncementVO>(page.getCurrent(), page.getPageSize())
                .setTotal(iPage.getTotal()).setRecords(listAnnouncementVOS);
    }

    @Override
    @Transactional
    public boolean deleteAnnouncements(List<Long> announcementIds) {
        announcementIds.forEach(e->{
            if(!this.removeById(e)){
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "删除失败");
            }
            QueryWrapper<Club> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("announcementId",e);
            Club club = clubMapper.selectOne(queryWrapper);
            if(club!=null){
                club.setAnnouncementId(null);
                clubMapper.updateById(club);
            }
        });
        return true;
    }

    @Override
    @Transactional
    public boolean addClubAnnouncement(ClubAnnouncement announcement) {
        if(this.baseMapper.insert(announcement)==0){
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "社团添加失败");
        }
        Club club = clubMapper.selectById(announcement.getClubId());
        if(club==null){
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "社团不存在");
        }
        club.setAnnouncementId(announcement.getId());
        clubMapper.updateById(club);
        return true;
    }

    private List<ListAnnouncementVO> convertAnnouncement(List<ClubAnnouncement> clubAnnouncements){
        return clubAnnouncements.stream().map(
                clubAnnouncement -> {
                    ListAnnouncementVO listAnnouncementVO = new ListAnnouncementVO();
                    listAnnouncementVO.setClubId(clubAnnouncement.getClubId());
                    listAnnouncementVO.setId(clubAnnouncement.getId());
                    listAnnouncementVO.setTitle(clubAnnouncement.getTitle());
                    listAnnouncementVO.setContent(clubAnnouncement.getContent());
                    listAnnouncementVO.setCreateTime(clubAnnouncement.getCreateTime());
                    listAnnouncementVO.setClubName(clubMapper.getClubName(clubAnnouncement.getClubId()));
                    listAnnouncementVO.setIsDelete(clubAnnouncement.getIsDelete());
                    return listAnnouncementVO;
                }
        ).toList();
    }
}




